package com.bsj.travel.mqtt.controller;

import com.bsj.travel.def.global.JsonResult;
import com.bsj.travel.def.mqtt.message.SendMqttMsg;
import com.bsj.travel.def.mqtt.message.node.MqttServerNode;
import com.bsj.travel.mqtt.service.MqttBrokerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author yinhao
 * @version 1.0
 * @description MQTT服务控制
 * @date 2023/11/9
 */
@RestController
@RequestMapping(value = "/broker")
public class MqttBrokerController {

    @Autowired
    private MqttBrokerService mqttBrokerService;

    /**
     * 获取全部服务节点
     * @return
     */
    @GetMapping(value = "/queryNodes")
    public JsonResult<List<MqttServerNode>> queryNodes() {
        return JsonResult.success(mqttBrokerService.getNodes());
    }

    /**
     * 获取所有节点在线的客户端数量
     * @return
     */
    @GetMapping(value = "/queryOnlineClientSize")
    public JsonResult<Long> queryOnlineClientSize() {
        return JsonResult.success(mqttBrokerService.getOnlineClientSize());
    }

    /**
     * 获取对应节点客户端在线数量
     * @param nodeName
     * @return
     */
    @GetMapping(value = "/queryNodeOnlineSize/{nodeName}")
    public JsonResult<Long> queryNodeOnlineSize(@PathVariable(value = "nodeName", required = false) String nodeName) {
        return JsonResult.success(mqttBrokerService.getOnlineClientSize(nodeName));
    }

    /**
     * 用于内部集群间MQTT消息下行
     * @param sendMqttMsg
     * @return
     */
    @PostMapping(value = "/sendMsg")
    public JsonResult<Boolean> sendMsg(@RequestBody SendMqttMsg sendMqttMsg) {
        return JsonResult.success(mqttBrokerService.sendMsg(sendMqttMsg));
    }

    /**
     * 用于内部集群间MQTT状态管理
     * @param sendMqttMsg
     * @return
     */
    @PostMapping(value = "/mqttConnectTake")
    public JsonResult<Boolean> mqttConnectTake(@RequestBody SendMqttMsg sendMqttMsg) {
        return JsonResult.success(mqttBrokerService.mqttConnectTake(sendMqttMsg.getUsername()));
    }
}
